import requests
import itchat
from itchat.content import *
import random

def get_response(msg):
    apiUrl = 'http://api.douqq.com/?key=SmcrdDhPd1NjdnFOdFo9WlRqc249SmV4RkJnQUFBPT0&msg='
    info = apiUrl + msg
    print(info)
    #apiUrl = 'http://www.tuling123.com/openapi/api'
    """data = {
        'key'    : KEY,
        'info'   : msg,
        'userid' : 'wechat-robot',
    }"""
    try:
        r = requests.get(info)
        return r.text
    except:
        return "出错了"

KEY = '04f44290d4cf462aae8ac563ea7aac16'
 
def get_chat_response(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key'    : KEY,
        'info'   : msg,
        'userid' : 'wechat-robot',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        return r.get('text')
    except:
        return

 
@itchat.msg_register(TEXT,isFriendChat=True)
def tuling_reply(msg):
    #defaultReply = 'I received: ' + msg['Text']
    #robots=['【自动回复】','【机器人】']
    msg_text = msg['Text']
    toUserName=msg['FromUserName']
    myName = itchat.get_friends()[0]['UserName']
    print("{}\nfrom:{}\n".format(msg_text,toUserName))
    if toUserName != myName:
        if msg['Text'][0] == '~':
            reply = "【自动回复】\n"+get_response(msg['Text'].lstrip('~'))#+random.choice(robots)
        else:
            reply = "【自动回复】\n"+get_chat_response(msg['Text'])
        itchat.send_msg(reply,toUserName)
    
    #return reply or defaultReply
 
itchat.auto_login()
itchat.run()